axios.defaults.baseURL = 'http://localhost:8080/'
//全局属性配置，在任意组件内可以使用this.$http获取axios对象
Vue.prototype.$http = axios
//======================axios的前置拦截器【拦截调用后端的请求====================//
axios.interceptors.request.use(res => {
    //从localStorage获取token
    let token = localStorage.getItem("token");
    if (token) {
        //设置到请求头
        res.headers["token"] = token;
    }
    return res;
}, error => {
    Promise.reject(error)
})
//======================axios的前置拦截器【拦截调用后端的请求】====================//
//======================axios的后置拦截器【处理后台登录拦截的结果】====================//
//后置拦截器一定会比回调函数先处理
axios.interceptors.response.use(res => {
    //后端响应的是没有登录的信息
    if (false === res.data.success && "noLogin" === res.data.msg) {
        localStorage.removeItem("token");
        localStorage.removeItem("logininfo");
        //跳转到登录页面
        location.href = "/login.html";
    } else if (false === res.data.success && "timeout" === res.data.msg) {
        localStorage.removeItem("token");
        localStorage.removeItem("logininfo");
        //跳转到登录页面
        location.href = "/login.html";
    }
    return res;
}, error => {
    Promise.reject(error)
})

//静态资源拦截器：拦截不发送axios请求的资源
//核心思路：如果你访问的不是login.html 也不是register.html。就要判断当前用户是否登录过
let url = location.href;//http://localhost/login.html
let path = url.substring(url.lastIndexOf("/"));
//url.indexOf("/callback.html") == -1就是访问的路径不是/callback.html
if (path != "/login.html" && path != "/register.html" && url.indexOf("/callback.html") == -1 && url.indexOf("/binder.html") == -1) {//不是登录，注册页面，也就是访问受限资源
    let logininfo = localStorage.getItem("logininfo");//本地存储中找到logininfo
    if (!logininfo) {//没有查到登录信息
        location.href = "/login.html";
    }
}

//将url地址栏后的参数解析成一个json对象
function parseUrlParams2Obj(url) {//xxxx?code=111&key=222 => {"code":111,"key":222}
    var obj = {};//设置一个空对象接收
    //截取
    let params = url.substring(url.indexOf("?") + 1);// code=111&key=222
    //分割参数
    let paramsArr = params.split("&");
    //遍历
    for (var i = 0; i < paramsArr.length; i++) {
        //每个参数
        let param = paramsArr[i];//code=111  or key=222
        let paramArr = param.split("=");
        //对象的属性名=属性值
        obj[paramArr[0]] = paramArr[1];

    }
    return obj;

}